import {createPatch} from 'diff';
import {parse} from 'diff2html';
import {DiffFile} from 'diff2html/lib/types';
import {Diff2HtmlUI} from 'diff2html/lib/ui/js/diff2html-ui';
import {useCallback, useEffect, useMemo, useRef, useState} from 'react';
import {Row} from 'react-bootstrap';
import useDebounce from '@/components/hook/useDebounce';
import {Func} from '@/types/utils';
import style from './style.module.scss';
import 'diff2html/bundles/css/diff2html.min.css';

function HomeIndex() {
    const [lText, setLText] = useState('');
    const [rText, setRText] = useState('');
    const diffView = useRef<HTMLDivElement>(null);
    const debounce = useDebounce(500);

    const handleChange = useCallback((value: string, label: string) => {
        debounce(() => {
            const handleMap: Record<string, Func> = {
                l: () => setLText(value),
                r: () => setRText(value)
            };
            handleMap[label] && handleMap[label]();
        });
    }, [debounce]);

    const diffFile = useMemo<DiffFile[]>(() => {
        const diffStr = createPatch('', lText, rText, '', '');
        return parse(diffStr);
    }, [lText, rText]);

    useEffect(() => {
        if (diffView.current) {
            const diff2htmlUi = new Diff2HtmlUI(diffView.current, diffFile, {
                drawFileList: false,
                matching: 'lines',
                outputFormat: 'side-by-side',
                highlight: false
            });
            diff2htmlUi.draw();
        }
    }, [diffFile]);

    return <div className={style['diff-root-wrapper']}>
        <div className={style['swiper-wrapper']}>
            <Row className={style['textarea-group']}>
                <textarea className={style['textarea']} onChange={e => handleChange(e.target.value, 'l')} />
                <textarea className={style['textarea']} onChange={e => handleChange(e.target.value, 'r')} />
            </Row>
            <div className={style['diff-wrapper-view']} ref={diffView} />
        </div>
    </div>;
}

export default HomeIndex;
